//
//  FirmwareViewController.swift
//  EasePods
//
//  Created by 李然 on 2024/5/7.
//

import UIKit
import EarbudsFunctions
import RxDataSources
import RxCocoa
import RxSwift

extension FirmwareSectionType {
    
    var header: String {
        switch self {
        case .box: return R.string.localizable.setting_firmware_earcase()
        case .ear: return R.string.localizable.setting_firmware_earbuds()
        }
    }
}

class FirmwareViewController: ViewController {
    
    lazy var viewModel = FirmwareViewModel(viewWillAppear: self.rx.viewWillAppear)
    
    override func makeUI() {
        super.makeUI()
        
        self.navigation.item.title = R.string.localizable.setting_firmware()
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        let dataSource = RxTableViewSectionedReloadDataSource<FirmwareSection> { (_, tableView, _, item) in
            let cell = tableView.dequeueReusableCell(withIdentifier: DefaultTableViewCell.reuseIdentifier) as! DefaultTableViewCell
            switch item {
            case .version(let cellModel):
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_firmware_version()
            case .macAddress(let cellModel):
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_firmware_mac_address()
            case .codeHash(let cellModel):
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_firmware_code_hash()
            case .reset(let cellModel):
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_firmware_recovery_title()
            case .upgrade(let cellModel):
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_firmware_upgrade_newest_version()
            }
            
            return cell
        }
        viewModel.dataSource.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: rx.disposeBag)
        tableView.rx.setDelegate(self).disposed(by: rx.disposeBag)
        
        tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in
            guard let `self` = self else { return }
            let section = self.viewModel.dataSource.value[indexPath.section]
            let item = section.items[indexPath.row]
            if section.type == .box {
                switch item {
                case .reset:
                    let view = ResetAlertView()
                    view.sureClick = {
                        UIView.dismissSheet()
                        BluetoothManager.shared.reset()
                    }
                    UIView.showSheet(with: view)
                case .upgrade(let cellModel):
                    print("")
                    if let version = cellModel.newVersion.value {
                        let vc = FirmwareUpgradeViewController(type: section.type, viewModel: FirmwareUpgradeViewModel(newVersion: version))
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                default:
                    break
                }
            } else {
                
            }
            
        }).disposed(by: rx.disposeBag)
    }
    

    lazy var tableView: TableView = {
        let view = TableView(frame: .zero, style: .grouped)
        view.backgroundColor = R.color.common_10_bg_page()
        view.register(DefaultTableViewCell.self, forCellReuseIdentifier: DefaultTableViewCell.reuseIdentifier)
        view.separatorColor = R.color.common_6_line()
        view.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        return view
    }()
    
}

extension FirmwareViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = View(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40))
        view.backgroundColor = R.color.common_10_bg_page()
        let label = Label()
        label.textColor = R.color.common_3_text()
        label.font = Fonts.systemFont(ofSize: 12)
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(20)
        }
        label.text = self.viewModel.dataSource.value[section].type.header
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = View(frame: CGRect(x: 0, y: 0, width: 300, height: 1))
        view.backgroundColor = .clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    class ResetAlertView: View {
        
        var sureClick:(() -> Void)?
        
        override func makeUI() {
            super.makeUI()
            
            snp.makeConstraints { make in
                make.width.equalTo(kScreenWidth)
            }
            
            let iconView = ImageView(image: R.image.img_firmware_reset_popup())
            addSubview(iconView)
            iconView.snp.makeConstraints { make in
                make.top.equalTo(20)
                make.centerX.equalToSuperview()
            }
            
            let label = Label()
            label.textColor = R.color.common_3_text()
            label.font = Fonts.systemFont(ofSize: 18)
            label.numberOfLines = 0
            label.textAlignment = .center
            label.text = R.string.localizable.setting_firmware_reset_title()
            addSubview(label)
            label.snp.makeConstraints { make in
                make.top.equalTo(iconView.snp.bottom).offset(20)
                make.centerX.equalToSuperview()
                make.width.equalTo(kScreenWidth - 32)
            }
            
            let tipLabel = Label()
            tipLabel.textColor = R.color.common_23_text_second()
            tipLabel.font = Fonts.systemFont(ofSize: 14)
            tipLabel.numberOfLines = 0
            tipLabel.textAlignment = .center
            tipLabel.text = R.string.localizable.setting_firmware_reset_tip()
            addSubview(tipLabel)
            tipLabel.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(label.snp.bottom).offset(12)
                make.width.equalTo(label)
            }
            
            let sureBtn = UIButton(type: .custom)
            sureBtn.layer.cornerRadius = 6
            sureBtn.layer.borderWidth = 1
            sureBtn.layer.borderColor = R.color.common_22_button_n()?.cgColor
            sureBtn.setTitle(R.string.localizable.common_confirm(), for: .normal)
            sureBtn.titleLabel?.font = Fonts.systemFont(ofSize: 16)
            sureBtn.setTitleColor(R.color.common_3_text(), for: .normal)
            sureBtn.setImageTitleLayout(.imgLeft, spacing: 8)
            sureBtn.rx.tap.subscribe(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                self.sureClick?()
            }).disposed(by: rx.disposeBag)
            
            let cancelBtn = UIButton(type: .custom)
            cancelBtn.layer.cornerRadius = 6
            cancelBtn.backgroundColor = R.color.common_22_button_n()
            cancelBtn.setTitle(R.string.localizable.common_cancel(), for: .normal)
            cancelBtn.titleLabel?.font = Fonts.systemFont(ofSize: 16)
            cancelBtn.setTitleColor(R.color.common_24_button_text(), for: .normal)
            cancelBtn.rx.tap.subscribe(onNext: { _ in
                UIView.dismissSheet()
            }).disposed(by: rx.disposeBag)
            
            let buttonStackView = StackView(arrangedSubviews: [sureBtn, cancelBtn])
            buttonStackView.spacing = 27
            buttonStackView.distribution = .fillEqually
            addSubview(buttonStackView)
            buttonStackView.snp.makeConstraints { make in
                make.top.equalTo(tipLabel.snp.bottom).offset(30)
                make.leading.equalTo(20)
                make.trailing.equalTo(-20)
                make.height.equalTo(48)
                make.bottom.equalTo(-20 - kSafeBottomMargin)
            }
        }
    }
}
